package com.ssy.lingxi.member.merchant.api.handler.validator;

import com.ssy.lingxi.member.merchant.api.handler.annotation.PhoneAnno;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 手机号码校验规则
 * <p>国际化时这里要增加校验规则</p>
 *
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-13
 */
public class PhoneValidator implements ConstraintValidator<PhoneAnno, String> {
    private boolean required = false;

    @Override
    public void initialize(PhoneAnno constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if ((value == null) || value.length()!=11) {
            return false;
        }

        String regex = "^(1[3-9]\\d{9}$)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(value);
        return m.matches();
    }
}
